var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller'),
    OperationController = require('../../../CBO/server/controllers/Operation.server.controller'),
    BizRecordController = require('../../../Barcode/server/controllers/BizRecord.server.controller.js'),
    RcvRecordController = require('../../../ProduceWork/server/controllers/RcvRecord.server.controller.js'),    
    DeliveryRecordController = require('../../../ProduceWork/server/controllers/DeliveryRecord.server.controller.js'),
	BaseFun = require('../../../Base/server/controllers/Function');	

//根据条码流水创建车间期间产量 -- ChenWei 2017.02.20
exports.createByBizRecord = function(bizRecordId){
    return new Promise(function(resolve, reject){
        var entity = entityCollection.getEntity("BizRecord");
        BizRecordController.findByPeriodOutput(bizRecordId).then(function(bizRecord){
            if(bizRecord) {
                //只有是物料条码才写车间产量
                if (bizRecord.BarcodeMaster.BarcodeType == BarcodeEnum.BarcodeType.ItemMaster.Value) {
                    //有返工工序的不记录
                    if (!bizRecord.BarcodeMaster.QCReworkOperation) {
                        bizRecord.BizDate = new Date(bizRecord.CollectDateTime.getFullYear(), bizRecord.CollectDateTime.getMonth(), bizRecord.CollectDateTime.getDate(), 0, 0, 0);

                        //创建期间产量数据
                        var periodRecord = {
                            ItemMaster: bizRecord.BarcodeMaster.ItemMaster,
                            DescSeg1: bizRecord.BarcodeMaster.DescSeg1,
                            DescSeg2: bizRecord.BarcodeMaster.DescSeg2,
                            DescSeg3: bizRecord.BarcodeMaster.DescSeg3,
                            Specification: bizRecord.BarcodeMaster.Specification,
                            Department: bizRecord.WorkLocation.Department,
                            BizDate: bizRecord.BizDate, //采集日期
                            BOH: 0,
                            BWIP: 0,
                            EWIP: 0, //期末在制:期初在制+当期转入-当期完工
                            EOH: 0, //期末库存
                            TransInQty: 0, //当期转入:如果是该部门的首序（*），则等于传入的数量，否则为0。
                            CompleteQty: 0, //当期完工:如果是该部门的尾序（*），则等于传入的数量，否则为0。
                            ReworkQty: 0, //当期返工:传入的返工量
                            ScriptQty: 0, //当期报废:传入的报废量。
                            RcvQty: 0, //当期入库
                            TransOutQty: 0 //当期转出
                        };

                        //注：由于现在流水记录还没有批量，全按数量1处理
                        if (bizRecord.QCStatus == QCEnum.QCStatus.Rework.Value) { //返工
                            periodRecord.ReworkQty = 1;
                        } else if (bizRecord.QCStatus == QCEnum.QCStatus.Scrap.Value) { //报废
                            periodRecord.ScriptQty = 1;
                        }

                        //判断是首序还是末序
                        OperationController.findByDepartmentAndItem(periodRecord.Department, periodRecord.ItemMaster).then(function(operations) {
                            if (operations.length > 0) {
                                // 首序
                                if (bizRecord.Operation._id == operations[0]._id) {
                                    periodRecord.TransInQty = 1; //转入量
                                } //末序
                                else if (bizRecord.Operation._id == operations[operations.length - 1]._id) {
                                    periodRecord.CompleteQty = 1; //完工量
                                }
                            }

                            //如果是计时工序
                            if (bizRecord.BarcodeMaster.Operation.IsTiming) {
                                //按“工序ID+条码主档ID”到“条码流水档”中查找记录，如果只有一条，则结束。（因为对计时工序，只在第二次刷芯片时记录）
                                entity.find({ BarcodeMaster: bizRecord.BarcodeMaster._id, Operation: bizRecord.Operation }, null, null, function(err, records) {
                                    if (!err) {
                                        if (records.length > 1) {
                                            exports.createPeriodRecord(periodRecord, "BizRecord").then(function(isSuccess){
                                                resolve(isSuccess);
                                            }).catch(function(err){
                                                reject(err);
                                            });
                                        } else {
                                            resolve(true);
                                        }
                                    } else {
                                        reject(err);
                                    }
                                });
                            } else {
                                exports.createPeriodRecord(periodRecord, "BizRecord").then(function(isSuccess){
                                    resolve(isSuccess);
                                }).catch(function(err){
                                    reject(err);
                                });
                            }
                        }).catch(function(err) {
                            reject(err);
                        });
                    }
                } else {
                    resolve(true);
                }
            }
        });
    });
};
exports.createByRcvRecord = function(rcvRecordId){
    return new Promise(function(resolve, reject){
        RcvRecordController.findByPeriodOutput(rcvRecordId).then(function(rcvRecord){
            if(rcvRecord){
                //只有是物料条码才写车间产量
                if(rcvRecord.BarcodeMaster.BarcodeType == BarcodeEnum.BarcodeType.ItemMaster.Value){
                    rcvRecord.RcvDateTime = new Date(rcvRecord.RcvDateTime.getFullYear(), rcvRecord.RcvDateTime.getMonth(), rcvRecord.RcvDateTime.getDate(), 0, 0, 0);
                    //创建期间产量数据
                     var periodRecord = {
                        ItemMaster: rcvRecord.BarcodeMaster.ItemMaster,
                        DescSeg1: rcvRecord.BarcodeMaster.DescSeg1,
                        DescSeg2: rcvRecord.BarcodeMaster.DescSeg2,
                        DescSeg3: rcvRecord.BarcodeMaster.DescSeg3,
                        // Specification: rcvRecord.BarcodeMaster.Specification,
                        Department: rcvRecord.WareHouse.Department,
                        BizDate: rcvRecord.RcvDateTime, //采集日期
                        BOH: 0,                 //期初库存
                        BWIP: 0,                //期初在制
                        EWIP: 0,                //期末在制:0
                        EOH: 0,                 //期末库存 期初库存+当期入库-当期转出。
                        TransInQty: 0,          //当期转入:0
                        CompleteQty: 0,         //当期完工:0
                        ReworkQty: 0,           //当期返工:传入的返工量
                        ScriptQty: 0,           //当期报废:传入的报废量。
                        RcvQty: rcvRecord.RcvQty,   //当期入库:传入数量
                        TransOutQty: 0          //当期转出:0
                    };
                    exports.createPeriodRecord(periodRecord, "RcvRecord").then(function(isSuccess){
                        resolve(isSuccess);
                    }).catch(function(err){
                        reject(err);
                    });
                }
                else{
                    resolve(true);
                }
            }
            else{
                reject(err);
            }
        });
    });
};
exports.createByDeliveryRecord = function(deliveryRecordId){
    return new Promise(function(resolve, reject){
        DeliveryRecordController.findByPeriodOutput(deliveryRecordId).then(function(deliveryRecord){
            if(deliveryRecord){
                var detailsEntity = entityCollection.getEntity("DeliveryDetails");
                var groupFieldName = {
                    ItemMaster: '$ItemMaster',
                    Department: '$Department',
                    DescSeg1: '$DescSeg1',
                    DescSeg2: '$DescSeg2',
                    DescSeg3: '$DescSeg3'
                };
                detailsEntity.aggregateSum(groupFieldName, 'Qty', {DeliveryRecord: deliveryRecordId}, function(err, data){
                    if(err){
                        reject(err);
                    }
                    else{
                        var bizDate = new Date(deliveryRecord.ReceiveTime.getFullYear(), deliveryRecord.ReceiveTime.getMonth(), deliveryRecord.ReceiveTime.getDate(), 0, 0, 0);
                        if(data.length > 0){
                            for(var sumRecord in data){
                                //创建期间产量数据
                                 var periodRecord = {
                                    ItemMaster: sumRecord.ItemMaster,
                                    DescSeg1: sumRecord.DescSeg1,
                                    DescSeg2: sumRecord.DescSeg2,
                                    DescSeg3: sumRecord.DescSeg3,
                                    // Specification: sumRecord.ItemMaster.Specification,
                                    Department: sumRecord.Department,
                                    BizDate: bizDate,       //采集日期:取配送记录上的接收时间
                                    BOH: 0,
                                    BWIP: 0,
                                    EWIP: 0,                //期末在制:期初在制+当期转入-当期完工
                                    EOH: 0,                 //期末库存
                                    TransInQty: 0,          //当期转入:如果是该部门的首序（*），则等于传入的数量，否则为0。
                                    CompleteQty: 0,         //当期完工:如果是该部门的尾序（*），则等于传入的数量，否则为0。
                                    ReworkQty: 0,           //当期返工:传入的返工量
                                    ScriptQty: 0,           //当期报废:传入的报废量。
                                    RcvQty: 0,              //当期入库
                                    TransOutQty: sumRecord.Qty          //当期转出
                                };
                                exports.createPeriodRecord(periodRecord);
                            }
                        };
                        resolve(true);
                    }
                });
            }
        });
    });
};
exports.createPeriodRecord = function(periodRecord, entityName){
    return new Promise(function(resolve, reject){
        var entity = entityCollection.getEntity('PeriodOutput');
        entity.findOne(
        	{
        		ItemMaster: periodRecord.ItemMaster,
        		Department: periodRecord.Department,
        		BizDate: periodRecord.BizDate,			//时间必须是0:00:00
        		DescSeg1: periodRecord.DescSeg1,
        		DescSeg2: periodRecord.DescSeg2,
        		DescSeg3: periodRecord.DescSeg3
        	},null, function(err, record){
        		if(!err){
        			if(record){
        				//如果有，更新
                        if(entityName==='BizRecord'){
                            record.ReworkQty += periodRecord.ReworkQty;
                            record.ScriptQty += periodRecord.ScriptQty;
                            record.TransInQty += periodRecord.TransInQty;
                            record.CompleteQty += periodRecord.CompleteQty;
                            record.RcvQty += periodRecord.RcvQty;
                            record.TransOutQty += periodRecord.TransOutQty;
                            //期末在制 = 期初在制 + 当期转入 - 当期完工
                            record.EWIP = periodRecord.BWIP + periodRecord.TransInQty - periodRecord.CompleteQty;
                            //期末库存 = 期初库存 + 当期入库 - 当期转出。???
                            record.EOH = periodRecord.BOH + periodRecord.RcvQty - periodRecord.TransOutQty; 
                        }
                        if(entityName==='RcvRecord'){
                            record.RcvQty += periodRecord.RcvQty;
                            //期末库存 = 期初库存 + 当期入库 - 当期转出。
                            record.EOH = periodRecord.BOH + periodRecord.RcvQty - periodRecord.TransOutQty;
                        }
        				
    					//修改车间期间产量
    					entity.update(record, function(err, record){
    						if(err){
    							BaseFun.errorLog('更新车间期间产量错误', err.message);
    							reject(err);
    						}
    						else{
    							resolve(true);
    						}
    					});
        			}
        			else{
        				//没找到则新增
        				//查找上一次的记录
        				entity.pageQuery({BizDate: {$lt: periodRecord.BizDate}}, {BizDate: -1}, null, 0, 1, function(err, records){
        					if(!err){
        						if(records.length > 0){
        							var preRecord = records[0];
        							periodRecord.BOH = preRecord.EOH;		//期初库存:从“当期产量表”中取同业务主键上一日期的期末库存，如找不到则为0。
        							periodRecord.BWIP = preRecord.EWIP;		//期初在制:从“当期产量表”中取同业务主键上一日期的期末在制，如找不到则为0。
        						}
                                if(entityName==='BizRecord'){
                                    //期末在制:期初在制+当期转入-当期完工
                                    periodRecord.EWIP = periodRecord.BWIP + periodRecord.TransInQty - periodRecord.CompleteQty;
                                }
                                if(entityName==='RcvRecord'){
                                    //期末库存 期初库存+当期入库-当期转出。
                                    periodRecord.EOH = periodRecord.BOH + periodRecord.RcvQty - periodRecord.TransOutQty;
                                }
    							//创建车间期间产量
    							entity.insert(periodRecord, function(err, record){
    								if(err){
    									BaseFun.errorLog('创建车间期间产量错误', err.message);
    									reject(err);
    								}
    								else{
    									resolve(true);
    								}
    							});
        					}
        					else{
        						BaseFun.errorLog('查找车间期间产量错误', err.message);
        						reject(err);
        					}
        				});
        			}
        		}
        	}
        );
    });
};

exports.insert = function(record, completeFun){
    var entity = entityCollection.getEntity('PeriodOutput');
    entity.insert(record, completeFun);
};

exports.update = function(record, completeFun){
    var entity = entityCollection.getEntity('PeriodOutput');
    entity.update(record, completeFun);
};

//通过时间段查找当期产量(按时间降序)
exports.getPeriodOutputByDate = function (startDay, endDay, department, completeFun) {
    
    var entity = entityCollection.getEntity("PeriodOutput");
    entity.find({BizDate:{$gte:startDay+" 00:00:00",$lte:endDay+" 23:59:59"},
        Department:department}, {BizDate: -1}
        , [{
        path: "ItemMaster",
        select: "Code Name"
    }], function (err, records) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询错误';
            newErr.message = '查询当期产量表失败！';
            completeFun(newErr);
        } else {
            completeFun(null, records);
        }
    });
};
